'use strict';

const Service = require('egg').Service;

class MenuService extends Service {
  async getMenuByRole() {
    const { ctx, app } = this;
    const roles = ctx.session.userinfo.roles;
    let adminRole = roles.find(el => el === 1);
    try {
      if (adminRole) {
        let arrs = await ctx.model.SysMenu.findAll();
        // console.log(arrs,555);
        return arrs.map(el => el.toJSON());
      }
      const { Op } = app.Sequelize;
      let list = roles.map(el => ({ roleId: el }))
      const result = await ctx.model.SysRole.findAll({
        where: {
          [Op.or]: list
        },
        include: [ctx.model.SysMenu]
      });
      let _list = result.map(el => el.toJSON());
      let arr = [];
      _list.forEach(el => {
        arr = [...arr, ...el.sys_menus];
      })
      return arr;
    } catch (error) {
      // console.log(88888888888888);
    }
    
  }
  formateRouter(list) {
    return list.map(item => {
      let menu = {};
      if (item.menuType === "M") {
        // menu.alwaysShow = true;
        menu.component = "Layout";
        menu.redirect = "noRedirect";
        menu.path = "/"+item.path;
      } else if (item.menuType === "C") {
        menu.component = item.component;
        menu.path = item.path;
      }

      if(item.isFrame === '0'){
        menu.path = item.path;
        menu.name = item.name;
        delete menu.redirect;
      }
      // menu.menu_type = item.menu
      // menu.path = "item.path";
      menu.menuId = item.menuId;
      menu.parentId = item.parentId;
      menu.name = item.path;
      menu.hidden = item.visible === "0" ? false : true;
      menu.meta = {
        title: item.menuName,
        icon: item.icon,
        noCache: item.isCache === "0" ? false : true
      }
      if (item.children instanceof Array) menu.children = this.formateRouter(item.children);
      return menu;
    })
  }
  async findAll(params = {}){
    const {ctx} = this;
    const list = await ctx.model.SysMenu.findAll(params);
    return list.map(el=>el.toJSON());
  }
}

module.exports = MenuService;
